package controlleur;

import eyrolles.EmployeForm;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import modele.Employe;
import modele.InterfaceEmployeModel;
import org.apache.struts.action.*;
import org.apache.struts.actions.DispatchAction;

public class GenericAction extends DispatchAction {

    protected InterfaceEmployeModel getModel(HttpServletRequest request) {
        ServletContext context = request.getServletContext();
        return (InterfaceEmployeModel) context.getAttribute("ModeleEmploye");
    }

    protected Employe getEmploye(ActionForm form) {
        EmployeForm eForm = (EmployeForm) form;

        Employe employe = new Employe();
        employe.setUsername(eForm.getUsername());
        employe.setPassword(eForm.getPassword());
        employe.setRoleid(Integer.parseInt(eForm.getRoleid()));
        employe.setDepid(Integer.parseInt(eForm.getDepid()));
        employe.setName(eForm.getName());
        employe.setPhone(eForm.getPhone());
        employe.setEmail(eForm.getEmail());

        return employe;
    }

    protected EmployeForm buildEmployeForm(Employe employe) {
        EmployeForm eForm = new EmployeForm();

        eForm.setUsername(employe.getUsername());
        eForm.setPassword(employe.getPassword());
        eForm.setRoleid(employe.getRoleid().toString());
        eForm.setDepid(employe.getDepid().toString());
        eForm.setName(employe.getName());
        eForm.setPhone(employe.getPhone());
        eForm.setEmail(employe.getEmail());

        return eForm;
    }

    protected ActionForward verificationIdentification(ActionMapping mapping,
                                                       HttpServletRequest request) {
        ActionMessages errors = new ActionMessages();

        // Teste sur l'identification de l'utilisateur
        HttpSession session = request.getSession();

        if (session.getAttribute("USER") == null) {
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                       new ActionMessage("errors.login.required"));

            // Retourner les erreurs eventuelles au formulaire d'origine
            saveErrors(request, errors);

            // Si jamais l'utilisateur n'est pas loggé, alors
            // on retourne directement à la page de login
            // avant d'effectuer la moindre requête
            return (mapping.findForward("login"));
        }
        return null;
    }
}